package com.nsgf.library.ui.page.home;

import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_DRAGGING;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WeatherDetailBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.FragmentReginNsgfHomeBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.HomeLabeRegionlListAdapter;
import com.nsgf.library.ui.adapter.HomeLabelRegionGateListAdapter;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.HomeMoreActivity;
import com.nsgf.library.ui.page.RainDetailActivity;
import com.nsgf.library.ui.page.ReservoirDetailsActivity;
import com.nsgf.library.ui.page.SearchProjectActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.WaterActivity;
import com.nsgf.library.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class HomeReginFragment extends BaseFragment {

    private HomeFragmentStates mStates;

    private FragmentReginNsgfHomeBinding mBinding;

    private HomeLabeRegionlListAdapter mAdapter;
    private HomeLabelRegionGateListAdapter mAdapterGate;
    private List<LibraryInfo> mDatas = new ArrayList<>();
    private List<LibraryInfo> mDatasGate = new ArrayList<>();

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(HomeFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new HomeLabeRegionlListAdapter(getContext());
        mAdapterGate = new HomeLabelRegionGateListAdapter(getContext());
        return new DataBindingConfig(R.layout.fragment_regin_nsgf_home, BR.vm, mStates).addBindingParam(BR.click, new ClickProxy()).addBindingParam(BR.adapter, mAdapter).addBindingParam(BR.adapterGate, mAdapterGate);
    }

    BottomSheetBehavior mBehavior;

    @Override
    public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);

        mBinding = (FragmentReginNsgfHomeBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);

        mAccountRequester.getProjectList().observe(this, projectList -> {

            if (200 == projectList.getResponseCode()) {

                JSONArray initArray = new JSONArray();
                for (UserInfo.ProjectListBean dataBean : projectList.getData()) {
                    String[] area = dataBean.getArea().split(",");
                    if (area.length == 2) {

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("lat", area[1]);
                        jsonObject.put("lon", area[0]);
                        jsonObject.put("positionName", dataBean.getFacilityName());
                        jsonObject.put("facilityName", dataBean.getFacilityName());
                        jsonObject.put("location", dataBean.getLocation());
                        jsonObject.put("pictureUrl", dataBean.getPictureUrl().replace("\\", ""));
                        jsonObject.put("projectCode", dataBean.getFacilityCode());
                        jsonObject.put("status", 6);
                        initArray.add(jsonObject);
                    }
                }
                callJavaScriptDrawInitPintFunction(initArray);
            } else {

                ToastUtils.showLongToast(projectList.getMsg());
            }
            mAccountRequester.getRainMonitoringList("");
        });


        mAccountRequester.getRainRecordList().observe(this, new Observer<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onChanged(ResponseStatus<List<LibraryInfo>> listResponseStatus) {

                if (listResponseStatus.getResponseCode() == 200) {
                    List<LibraryInfo> list = new ArrayList<>();
                    if (listResponseStatus.getData().size() > 4) {
                        for (int i = 0; i < 4; i++) {
                            list.add(listResponseStatus.getData().get(i));
                        }
                    } else {
                        list = listResponseStatus.getData();
                    }
                    mStates.listGate.set(list);
                } else {
                    ToastUtils.showShortToast(listResponseStatus.getMsg());
                }
                mAccountRequester.getWaterMonitoringList("");
            }
        });


        mAccountRequester.getWaterRecordList().observe(this, listResponseStatus -> {

            if (listResponseStatus.getResponseCode() == 200) {
                List<LibraryInfo> list = new ArrayList<>();
                if (listResponseStatus.getData().size() > 4) {
                    for (int i = 0; i < 4; i++) {
                        list.add(listResponseStatus.getData().get(i));
                    }
                } else {
                    list = listResponseStatus.getData();
                }
                mStates.list.set(list);
            } else {
                ToastUtils.showShortToast(listResponseStatus.getMsg());
            }
        });
        mAdapter.notifyDataSetChanged();
        mAdapterGate.notifyDataSetChanged();


        mBehavior = BottomSheetBehavior.from(mBinding.bottomSheet);
        mBehavior.setState(STATE_COLLAPSED);
        mBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {

                if (newState == STATE_HIDDEN) {
                    mBehavior.setState(STATE_COLLAPSED);
                    mBinding.ivNsgfHomeSheet.setImageResource(R.drawable.ic_nsgf_home_sheet_up);
                } else if (newState == STATE_COLLAPSED) {
                    mBinding.ivNsgfHomeSheet.setImageResource(R.drawable.ic_nsgf_home_sheet_up);
                } else {
                    if (newState != STATE_DRAGGING)
                        mBinding.ivNsgfHomeSheet.setImageResource(R.drawable.ic_nsgf_home_sheet_down);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });


        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                mAccountRequester.getReservoirByName("");
            }
        });
        mBinding.webView.getWebView().addJavascriptInterface(new WebViewInterface(), "android");


        mAdapterGate.setOnItemClickListener((viewId, item, position) -> startActivity(new Intent()
                .putExtra("title", item.getReservoirName())
                .putExtra("projectCode", item.getProjectCode())
                .putExtra("info", item)
                .setClass(getActivity(), RainDetailActivity.class)));
        mAdapter.setOnItemClickListener((viewId, item, position) -> startActivity(new Intent()
                .putExtra("title", item.getReservoirName())
                .putExtra("projectCode", item.getWaterLevelCode())
                .putExtra("info", item)
                .setClass(getActivity(), WaterActivity.class)));


        mAccountRequester.queryWeatherForecast();
        mAccountRequester.getWeatherDetailBean().observe(this, new Observer<ResponseStatus<WeatherDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<WeatherDetailBean> weatherDetailBeanResponseStatus) {

                if (weatherDetailBeanResponseStatus.getResponseCode() == 200) {

                    WeatherDetailBean.DataBeanX.DataBean.ForecastBean forecastBean = weatherDetailBeanResponseStatus.getData().getData().getData().getForecast().get(weatherDetailBeanResponseStatus.getData().getData().getData().getForecast().size() - 1);
                    mStates.weatherTitle.set(forecastBean.getType() + " " + forecastBean.getLow() + " ~ " + forecastBean.getHigh() + "  I  " + forecastBean.getFx() + forecastBean.getFl());
                    mStates.weatherIcont.set(getItemIcon(forecastBean.getType()));

                } else {
                    mStates.weatherTitle.set("晴26℃  I  东南风2级");
                }

            }
        });

    }

    private void callJavaScriptDrawInitPintFunction(JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("drawInitPintProject(" + list + ");", null);

    }

    public static class HomeFragmentStates extends StateHolder {

        public final State<String> projectName = new State<>(UserInfo.getInstance().getProjectName());
        public final State<String> name = new State<>(UserInfo.getInstance().getName());

        public final State<List<LibraryInfo>> list = new State<>(new ArrayList<>());
        public final State<List<LibraryInfo>> listGate = new State<>(new ArrayList<>());
        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<ClockInBean.DataBean> statistics = new State<>(null);

        public final State<List<UserInfo.ProjectListBean>> listMap = new State<>(new ArrayList<>());

        public final State<String> weatherTitle = new State<>("");
        public final State<Drawable> weatherIcont = new State<>(null);
    }


    public Drawable getItemIcon(String type) {
        switch (type) {
            case "暴雪":
                return getActivity().getResources().getDrawable(R.drawable.baoxue);
            case "暴雨":
                return getActivity().getResources().getDrawable(R.drawable.baoyu);
            case "大暴雨":
                return getActivity().getResources().getDrawable(R.drawable.dabaoyu);
            case "大雪":
                return getActivity().getResources().getDrawable(R.drawable.daxue);
            case "大雨":
                return getActivity().getResources().getDrawable(R.drawable.dayu);
            case "冻雨":
                return getActivity().getResources().getDrawable(R.drawable.dongyu);
            case "多云":
                return getActivity().getResources().getDrawable(R.drawable.duoyun);
            case "浮沉":
                return getActivity().getResources().getDrawable(R.drawable.fuchen);
            case "雷阵雨":
                return getActivity().getResources().getDrawable(R.drawable.leizhenyu);
            case "雷阵雨伴有冰雹":
                return getActivity().getResources().getDrawable(R.drawable.lzybybb);
            case "霾":
                return getActivity().getResources().getDrawable(R.drawable.mai);
            case "强沙尘暴":
                return getActivity().getResources().getDrawable(R.drawable.qiangshachenbao);
            case "晴":
                return getActivity().getResources().getDrawable(R.drawable.qing);
            case "沙暴":
                return getActivity().getResources().getDrawable(R.drawable.shabao);
            case "沙尘暴":
                return getActivity().getResources().getDrawable(R.drawable.shachenbao);
            case "特大暴雨":
                return getActivity().getResources().getDrawable(R.drawable.tedabaoyu);
            case "雾":
                return getActivity().getResources().getDrawable(R.drawable.wu);
            case "小雪":
                return getActivity().getResources().getDrawable(R.drawable.xiaoxue);
            case "小雨":
                return getActivity().getResources().getDrawable(R.drawable.xiaoyu);
            case "阴":
                return getActivity().getResources().getDrawable(R.drawable.yin);
            case "雨夹雪":
                return getActivity().getResources().getDrawable(R.drawable.yujiaxue);
            case "阵雪":
                return getActivity().getResources().getDrawable(R.drawable.zhenxue);
            case "阵雨":
                return getActivity().getResources().getDrawable(R.drawable.zhenyu);
            case "中雪":
                return getActivity().getResources().getDrawable(R.drawable.zhongxue);
            case "中雨":
                return getActivity().getResources().getDrawable(R.drawable.zhongyu);
            default:
                return getActivity().getResources().getDrawable(R.drawable.qing);
        }
    }


    public class ClickProxy {

        public void search() {
            startActivity(new Intent().setClass(getActivity(), SearchProjectActivity.class));
        }

        public void moreWater() {
            startActivity(new Intent()
                    .putExtra("type", 0)
                    .putExtra("title", "水情监测")
                    .setClass(getActivity(), HomeMoreActivity.class));
        }

        public void moreRainfall() {
            startActivity(new Intent()
                    .putExtra("type", 1)
                    .putExtra("title", "雨量监测")
                    .setClass(getActivity(), HomeMoreActivity.class));
        }
    }

    /**
     * Js调用的JavascriptInterface
     */
    public class WebViewInterface {

        @JavascriptInterface
        public void openDetails(String src) {
            Gson gson = new Gson();
            ClockInBean.DataBean.LateAndEarlyListBean info = gson.fromJson(src, ClockInBean.DataBean.LateAndEarlyListBean.class);

            startActivity(new Intent()
                    .putExtra("info", info)
                    .setClass(getActivity(),
                            ReservoirDetailsActivity.class));
        }
    }
}
